package demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import demo.BusinessType;
import demo.CustomException;
import demo.ExceptionEnum;
import demo.entity.SystemNormalUser;
import demo.idempotent.annotation.RepeatSubmit;
import demo.log.Log;
import demo.service.SystemNormalUserService;
import demo.vo.R;
import demo.vo.SystemNormalUserSaveVo;
import demo.vo.SystemNormalUserUpdateVo;
import demo.vo.SystemNormalUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

/**
 * <p>
 * 普通用户-前端控制器
 * </p>
 *
 * @author TangZibo
 * @since 2021-04-19
 */
@Api(value = "普通用户控制器", tags = "系统管理模块-普通用户管理接口")
@RestController
@Slf4j
@Validated
@RequestMapping("/systemNormalUser")
public class SystemNormalUserController {

    private SystemNormalUserService systemNormalUserService;

    @Autowired
    public SystemNormalUserController(SystemNormalUserService systemNormalUserService) {
        this.systemNormalUserService = systemNormalUserService;
    }

    /**
     * 添加普通用户
     * @param saveVo
     * @return
     */
    @Log(title = "普通用户管理", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    @ApiOperation(value = "添加普通用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public R<SystemNormalUser> save(@RequestBody @Validated SystemNormalUserSaveVo saveVo) {
        log.info(saveVo.toString());
        //校验信用代码唯一
        int count = systemNormalUserService.count(new QueryWrapper<SystemNormalUser>().eq("username", saveVo.getUsername()));
        if (count != 0) {
            throw new CustomException("用户已存在");
        }

        //封装系统用户对象
        SystemNormalUser systemNormalUser = new SystemNormalUser();
        BeanUtil.copyProperties(saveVo, systemNormalUser, true);

        //调用注册新增服务
        systemNormalUserService.registerNormalUser(saveVo, systemNormalUser);

        return R.success(systemNormalUser);
    }

    /**
     * 修改普通用户
     * @param updateVo
     * @return
     */
    @Log(title = "普通用户管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping
    @ApiOperation(value = "修改普通用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public R<Boolean> update(@RequestBody @Validated SystemNormalUserUpdateVo updateVo) {
        SystemNormalUser bean = new SystemNormalUser();
        BeanUtil.copyProperties(updateVo, bean);
        boolean updateResult = systemNormalUserService.updateById(bean);
        if (!updateResult) {
            throw new CustomException("更新普通用户失败");
        }
        return R.success(updateResult);
    }

    /**
     * 查询普通用户详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询普通用户详情", notes = "查询普通用户详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public R<SystemNormalUser> get(
            @PathVariable @Min(value = 0, message = "ID不能小于0") Long id) {
        SystemNormalUser bean = systemNormalUserService.getOne(new QueryWrapper<SystemNormalUser>().eq("id", id));
        return R.success(bean);
    }

    /**
     * 分页查询普通用户
     * @param pageSize
     * @param pageNum
     * @param vo
     * @return
     */
    @GetMapping("/page/{pageSize}/{pageNum}")
    @ApiOperation(value = "分页查询普通用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public R<IPage<SystemNormalUser>> page(
            @PathVariable("pageSize") Integer pageSize, @PathVariable("pageNum") Integer pageNum, SystemNormalUserVo vo) {
        IPage<SystemNormalUser> page = new Page<>(pageNum, pageSize);
        QueryWrapper queryWrapper = buildQueryWrapper(vo);
        IPage<SystemNormalUser> beanIPage = systemNormalUserService.page(page, queryWrapper);
        return R.success(beanIPage);
    }

    /**
     * 删除普通用户
     * @param id
     * @return
     */
    @Log(title = "普通用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除普通用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 500, message = "请求失败")
    })
    public R<Boolean> delete(@PathVariable @Min(value = 0, message = "id不能小于0") Long id) {
        boolean removeResult = systemNormalUserService.removeById(id);
        if (!removeResult) {
            throw new CustomException("删除普通用户失败");
        }
        return R.success(removeResult);
    }

    /**
     * 根据所属类型获取条件构造器
     *
     * @return
     */
    private QueryWrapper<SystemNormalUser> buildQueryWrapper(SystemNormalUserVo vo) {

        QueryWrapper<SystemNormalUser> wrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(vo.getUsername())) {
            wrapper.like("username", vo.getUsername().trim());
        }
        if (StrUtil.isNotBlank(vo.getNickname())) {
            wrapper.like("nickname", vo.getNickname().trim());
        }
        if (StrUtil.isNotBlank(vo.getDistrictCode())) {
            wrapper.like("district_code", vo.getDistrictCode().trim());
        }
        if (StrUtil.isNotBlank(vo.getPhone())) {
            wrapper.like("phone", vo.getPhone().trim());
        }
        if (StrUtil.isNotBlank(vo.getEmail())) {
            wrapper.like("email", vo.getEmail().trim());
        }

        wrapper.orderByDesc("created_time");
        return wrapper;
    }

}

